/*
 * ==========================================================================*\
 * | $Id$
 * |*-------------------------------------------------------------------------*|
 * | Copyright (C) 2009 Virginia Tech | | This file is part of CloudSpace. | |
 * CloudSpace is free software; you can redistribute it and/or modify | it under
 * the terms of the GNU General Public License as published | by the Free
 * Software Foundation; either version 3 of the License, or | (at your option)
 * any later version. | | CloudSpace is distributed in the hope that it will be
 * useful, | but WITHOUT ANY WARRANTY; without even the implied warranty of |
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | GNU General
 * Public License for more details. | | You should have received a copy of the
 * GNU General Public License | along with CloudSpace; if not, see
 * <http://www.gnu.org/licenses/>.
 * \*==========================================================================
 */

package cloudspace.controlpanel;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericComposer;
import org.zkoss.zul.Div;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import cloudspace.config.CloudSpaceConfiguration;


// -------------------------------------------------------------------------
/**
 * Manages interactions between the system configuration dialog and the
 * CloudSpace configuration model.
 * 
 * @author Tony Allevato
 * @author Last changed by $Author$
 * @version $Revision$, $Date$
 */
public class SystemConfigurationController extends GenericComposer
{

    // ~ Static/instance variables .............................................

    private CloudSpaceConfiguration config;

    private Window systemConfigWindow;

    private Listbox logLevelBox;

    private Textbox workspacePathField;

    private Textbox workPathField;

    private Div messagePanel;

    private Label messageLabel;

    private static final long serialVersionUID = 534061368980367148L;

    private static final Logger log = Logger.getLogger( SystemConfigurationController.class );


    // ~ Methods ...............................................................

    // ----------------------------------------------------------
    @SuppressWarnings("unchecked")
    @Override
    public void doAfterCompose( Component component ) throws Exception
    {
        super.doAfterCompose( component );

        config = CloudSpaceConfiguration.getInstance();

        systemConfigWindow = (Window)component;
        workspacePathField = (Textbox)systemConfigWindow.getFellow( "workspacePathField" );
        workspacePathField.setValue( config.getStorageLocation().getPath() );
        workPathField = (Textbox)systemConfigWindow.getFellow( "workPathField" );
        workPathField.setValue( config.getWorkLocation().getPath() );
        messagePanel = (Div)systemConfigWindow.getFellow( "messagePanel" );
        messageLabel = (Label)systemConfigWindow.getFellow( "messageLabel" );
        logLevelBox = (Listbox)systemConfigWindow.getFellow( "logLevels" );
        Level currentLevel = Logger.getRootLogger().getLevel();
        List<Listitem> levelListItems = (List<Listitem>)logLevelBox.getChildren();
        for ( Listitem level : levelListItems )
        {
            String levelName = level.getLabel();
            level.setValue( Level.toLevel( levelName ) );
            if ( level.getValue().equals( currentLevel ) )
            {
                logLevelBox.selectItem( level );
                break;
            }
        }
    }


    // ----------------------------------------------------------
    /**
     * Called when the user clicks the Save button in the dialog.
     * 
     * @param event
     *            a ZK event
     */
    public void onSave( Event event )
    {
        // Try to set the workspace path, which will cause the server to
        // attempt to write to that location. If there is an exception (for
        // example, because of filesystem permissions), we must report that to
        // the user.

        try
        {
            config.setStorageLocation( new File( workspacePathField.getText() ) );
            config.setWorkLocation( new File( workPathField.getText() ) );
        }
        catch ( IOException e )
        {
            log.warn( "System configuration was not saved because there was "
                + "an error accessing the new workspace location", e );

            // Display permissions message.

            messageLabel.setValue( e.getMessage() );
            messagePanel.setSclass( "info-panel info-panel-error" );
            messagePanel.setVisible( true );

            return;
        }

        messageLabel.setValue( "System configuration successfully updated." );
        messagePanel.setSclass( "info-panel info-panel-success" );
        messagePanel.setVisible( true );

        Level newLogLevel = (Level)logLevelBox.getSelectedItem().getValue();
        Logger.getRootLogger().setLevel( newLogLevel );
        log.info( "System configuration successfully updated" );
    }

}
